<template>
	<view class="" @click.stop>
		<view class="voiceread-every" @click.stop>
			<view class="voiceread-box-head" @click.stop>
				<view style="margin:0 -30px 0 10px;">放慢语速</view>
				<view class="voiceread-slider-container">
					<slider :min="0.5" :max="2" :step="0.1" :value="voiceReadStore.rate" @change="onRateChange"
						activeColor="#ff0307" backgroundColor="#bababa" />
				</view>

				<view style="margin-left: -40px;">加快语速</view>
				<view class="timing" @click.stop="gotoTiming">
					<text class="iconfont icon-shijian4"></text>
					<view class="">{{voiceReadStore.timing}}</view>
				</view>
			</view>
			<view class="voiceread-box-center" @click.stop>
				<view class="voiceread-title">离线语音</view>
				<scroll-view class="voiceread-scroll" show-scrollbar="false" scroll-x="true" @scroll="scroll"
					scroll-left="120">
					<view :class="{'view-actice': voiceReadStore.voiceType === 'male'}" @click.stop="changeVoiceType('male')">男主播</view>
					<view :class="{'view-actice': voiceReadStore.voiceType === 'female'}" @click.stop="changeVoiceType('female')">青年女声</view>
					<view :class="{'view-actice': voiceReadStore.voiceType === 'youngMale'}" @click.stop="changeVoiceType('youngMale')">青年男声</view>
					<view :class="{'view-actice': voiceReadStore.voiceType === 'femaleHost'}" @click.stop="changeVoiceType('femaleHost')">女主播</view>
					<view :class="{'view-actice': voiceReadStore.voiceType === 'child'}" @click.stop="changeVoiceType('child')">娃娃音</view>
				</scroll-view>
			</view>
			<view class="voiceread-box-backend" @click.stop="exitVoiceRead">
				<text class="iconfont icon-guanji1"></text>
				<view>退出语音朗读</view>
			</view>
		</view>
		
	</view>
</template>

<script setup>
	import '@/common/iconfont.css'
	import { ref, onMounted, onUnmounted, watch } from 'vue';
	import {
		useNovelStore
	} from '../../common/novel/novel.js';
	import {
		useTextLayoutStore
	} from '../../common/novel/textLayout.js';
	import {
		useVoiceReadStore
	} from '../../common/love/leason.js';
	
	// 导入离线TTS插件
	let TTSSpeech;
	try {
		TTSSpeech = uni.requireNativePlugin("MT-TTS-Speech");
		console.log('成功加载MT-TTS-Speech模块');
	} catch (error) {
		console.error('加载MT-TTS-Speech模块失败:', error);
		TTSSpeech = null;
		// 显示错误提示
		setTimeout(() => {
			uni.showModal({
				title: '提示',
				content: '当前运行的基座不包含原生插件[MT-TTS-Speech]，请在manifest中配置该插件，重新制作包括该原生插件的自定义运行基座',
				showCancel: false
			});
		}, 1000);
	}
	
	// 检查TTS插件是否可用
	const isTTSAvailable = ref(!!TTSSpeech);
	
	// 初始化 store
	const store = useNovelStore();
	const textLayoutStore = useTextLayoutStore();
	const voiceReadStore = useVoiceReadStore();
	
	// 组件挂载时
	onMounted(() => {
		// 获取已安装的TTS引擎列表（可选）
		if (isTTSAvailable.value) {
			try {
				TTSSpeech.getInstallTTS(list => {
					console.log('已安装的TTS引擎:');
					list.forEach(v => console.log(`引擎名: ${v.label} 包名: ${v.name}`));
				});
			} catch (error) {
				console.error('获取TTS引擎列表失败:', error);
			}
		} else {
			console.log('TTS插件不可用，无法获取引擎列表');
		}
		
		// 发送事件，通知已准备好
		uni.$emit('voiceReadReady', {
			rate: voiceReadStore.rate,
			voiceType: voiceReadStore.voiceType
		});
		
		// 添加阻止点击穿透的处理
		const voicereadComponent = document.querySelector('.voiceread-every');
		if (voicereadComponent) {
			voicereadComponent.addEventListener('click', (event) => {
				event.stopPropagation();
			});
		}
	});
	
	// 退出语音朗读
	const exitVoiceRead = (e) => {
		// 阻止事件冒泡
		if (e) e.stopPropagation();
		
		// 发送退出事件
		uni.$emit('exitVoiceRead');
		
		// 设置标记表明需要停止朗读
		voiceReadStore.shouldStopOnClose = true;
		
		// 直接设置状态关闭组件
		store.isVoiceread = false;
		console.log('退出语音朗读，设置isVoiceread:', store.isVoiceread);
	};
	
	// 切换到定时功能
	const gotoTiming = (e) => {
		if (e) e.stopPropagation();
		
		// 直接设置状态关闭语音朗读组件
		store.isVoiceread = false;
		
		// 打开定时组件
		store.isTiming = true;
		console.log('切换到定时功能');
	};
	
	// 调整语速
	const onRateChange = (e) => {
		// 阻止事件冒泡
		if (e) e.stopPropagation();
		
		const rate = e.detail.value;
		
		// 更新voiceReadStore中的语速
		voiceReadStore.rate = rate;
		
		// 检查插件是否可用
		if (isTTSAvailable.value) {
			try {
				// 将rate(0.5-2.0)转换为TTS需要的语速(0-100)
				const ttsSpeed = Math.round((rate - 0.5) * 100 / 1.5);
				
				// 设置TTS语速
				TTSSpeech.setSpeed(ttsSpeed);
				console.log(`设置语速: ${rate} (转换为TTS速度: ${ttsSpeed})`);
			} catch (error) {
				console.error('设置TTS语速失败:', error);
			}
		}
		
		// 发送事件，通知语速变化 - 不使用voiceReadStore的在线实现
		// uni.$emit('voiceRateChange', rate);
	};
	
	// 切换声音类型
	const changeVoiceType = (type, e) => {
		// 阻止事件冒泡
		if (e) e.stopPropagation();
		
		// 更新voiceReadStore中的声音类型
		voiceReadStore.voiceType = type;
		
		// 检查插件是否可用
		if (isTTSAvailable.value) {
			try {
				// 根据声音类型设置音调
				let ttsPitch = 50; // 默认音调
				
				switch (type) {
					case 'female':
						ttsPitch = 60; // 女声音调高一些
						break;
					case 'male':
						ttsPitch = 40; // 男声音调低一些
						break;
					case 'youngMale':
						ttsPitch = 50; // 青年男声
						break;
					case 'femaleHost':
						ttsPitch = 65; // 女主播
						break;
					case 'child':
						ttsPitch = 75; // 儿童声音
						break;
				}
				
				// 设置TTS音调
				TTSSpeech.setPitch(ttsPitch);
				console.log(`切换声音类型: ${type} (设置音调: ${ttsPitch})`);
				
				// 如果正在朗读，需要重新开始朗读以应用新的声音设置
				if (voiceReadStore.isReading && !voiceReadStore.isPaused) {
					try {
						// 先停止当前朗读
						TTSSpeech.stop();
						
						// 重新开始朗读
						setTimeout(() => {
							// 使用menu.vue中的playTTS函数通过事件触发
							uni.$emit('restartTTS');
						}, 100);
					} catch (error) {
						console.error('重新开始朗读失败:', error);
					}
				}
			} catch (error) {
				console.error('设置TTS音调失败:', error);
			}
		}
		
		// 发送事件，通知声音类型变化 - 不使用voiceReadStore的在线实现
		// uni.$emit('voiceTypeChange', type);
	};
	
	// 滚动处理
	const scroll = (e) => {
		// 阻止事件冒泡
		if (e) e.stopPropagation();
		// 滚动处理逻辑
	};
</script>

<style lang="scss">
	@import '/common/novel/novel.scss';

	.voiceread-every {
		width: 100vw;
		height: 40vh;
		position: absolute;
		bottom: 0px;
		background-color: var(--bg-color);
		z-index: 1000; /* 确保层级足够高 */

		.voiceread-box-head {
			width: 100%;
			height: 80px;
			//两边均分
			display: flex;
			justify-content: space-between;
			align-items: center;

			view {
				font-size: 12px;
				color: var(--font-color);
			}

			.voiceread-slider-container {
				height: 36px;
				width: calc(100vw - 180px);
			}

			.timing {
				width: 10vw;
				height: 100%;
				margin: 0 10px 0 -30px;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				text {
					font-size: 24px;
					color: var(--font-color);
				}
			}
		}

		.voiceread-box-center {
			width: 100%;
			height: 80px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.voiceread-title {
				margin: 0 -20px 0 10px;
				font-size: 12px;
				color: var(--font-color);
			}

			.voiceread-scroll {
				width: 75%;
				height: 100%;
				margin: 0 20px 0 -30px;
				white-space: nowrap;
				view {
					width: 50px;
					height: 30px;
					margin-top: 26px;
					display: inline-block;
					/* 行内块元素，支持宽高和边框 */
					padding: 0 20px;
					/* 左右内边距 */
					line-height: 30px;
					/* 垂直居中（高度与行高一致） */
					text-align: center;
					/* 水平居中 */
					font-size: 12px;
					color: var(--font-color);

				}

				.view-actice {
					color: red;
					border: 1px solid red;
					/* 红色边框线 */
					border-radius: 5px;
				}

				&::-webkit-scrollbar {
					display: none;
				}

				/* 隐藏滚动条（Firefox） */
				scrollbar-width: none;
			}
		}

		.voiceread-box-backend {
			width: 100%;
			height: 100px;
			margin-top: calc(40vh - 260px);
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			text {
				color: white;
				font-size: 30px;
			}

			view {
				font-size: 12px;
				color: var(--font-color);
			}
		}
	}
</style>